package com.duoduo.sanguoshanews;

import java.io.IOException;

import com.duoduo.bean.NewsDetail;
import com.duoduo.data.WebData;
import com.duoduo.db.DBHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class NewDetailActivity extends Activity {
	private DBHelper databaseHelper;
	private NewsDetail newsDetail;
	private TextView title_view;
	private TextView pubdate_view;
	private TextView content_view;
	private Handler handler;
	private ProgressDialog progressDialog;
	private String title;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_detail);
		handler = new Handler();
		title_view = (TextView) findViewById(R.id.title_view);
		pubdate_view = (TextView) findViewById(R.id.pubdate_view);
		content_view = (TextView) findViewById(R.id.content_view);
		databaseHelper = new DBHelper(this);
		Intent intent = getIntent();
		String url = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		newsDetail = databaseHelper.getNewsDetail(url);
		if (newsDetail == null) {
			getNewsDetailFromWeb(url);
		} else {
			title_view.setText(newsDetail.getTitle());
			pubdate_view.setText(newsDetail.getPubdate());
			content_view.setText(newsDetail.getContent());
		}
	}

	public void getNewsDetailFromWeb(final String url) {
		progressDialog = ProgressDialog.show(this, "载入中", "新闻加载中，请稍后...");
		new Thread() {
			public void run() {
				final NewsDetail newsDetail;
				try {
					newsDetail = WebData.getNewsDetail(NewDetailActivity.this,
							url,title);
					handler.post(new Runnable() {
						public void run() {
							if (newsDetail != null) {
								title_view.setText(newsDetail.getTitle());
								pubdate_view.setText(newsDetail.getPubdate());
								content_view.setText(newsDetail.getContent());
							} else {
								Log.i("web", "newsDetail is null");
							}
							progressDialog.dismiss();
							Toast.makeText(NewDetailActivity.this, "更新完成",
									Toast.LENGTH_SHORT).show();
						}

					});
					if (newsDetail != null) {
						databaseHelper.saveNewsDetail(newsDetail);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}.start();
	}
}
